<template>
  <div class="box">
    <van-nav-bar
      title="咨询客服"
      left-arrow
      @click-left="goBack"
      class="header"
    />
    <div class="content" ref="content">
      <div
        v-for="(item, index) in messages"
        :key="index"
        :class="{ mine: item.isMine, jqr: !item.isMine }"
      >
        <div class="img"></div>
        <div class="text">{{ item.text }}</div>
      </div>
    </div>
    <div class="footer">
      <input
        id="input"
        type="text"
        placeholder="请输入文字"
        v-model="mymessage"
        @keyup.enter="sendMessage"
      />
      <van-button type="success" id="btn" @click="sendMessage">发送</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';

const { proxy } = getCurrentInstance();
const goBack = () => { proxy.$router.go(-1); };

const message = ref('');
const messages = ref([
  {
    text: '您好，我是菲菲，非常欢迎您的到来，有什么想和我聊聊的吗？',
    isMine: false
  }
]);
const content = ref(null);
const mymessage=ref('')

const sendMessage = async () => {
  console.log('Sending message:', mymessage.value);
  // 添加用户消息
  messages.value.push({ text: mymessage.value, isMine: true });
  message.value = '';

  // 清空输入框
  await scrollToEnd();
  // 发送请求到服务器

  console.log(JSON.stringify(mymessage.value));
  try {
    const response = await fetch('/api/robot.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message: mymessage.value }),
    });
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const res = await response.json();
    if (res.code === 0) {
      alert(res.msg);
    } else {
      messages.value.push({ text: res.data, isMine: false });
      await scrollToEnd();
    }
  } catch (error) {
    console.error('Error sending message:', error);
  }
};

const scrollToEnd = async () => {
  if (content.value) {
    await nextTick();
    content.value.scrollTop = content.value.scrollHeight;
  }
};

onMounted(() => {
  scrollToEnd();
});
</script>


<style>
@import url("/assets/css/robot.css");
</style>